package org.jeecg.modules.syncdata.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.jeffreyning.mybatisplus.service.IMppService;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.modules.syncdata.entity.SyncCompensate;
import org.jeecg.modules.syncdata.mapper.SyncCompensateMapper;
import org.jeecg.modules.syncdata.service.SyncCompensateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 同步补偿服务实现类
 *
 * @author zhanglei01
 * @date 2022/03/16
 */
@Slf4j
@Service
public class SyncCompensateServiceImpl extends ServiceImpl<SyncCompensateMapper, SyncCompensate>
        implements SyncCompensateService {

    private static final Integer PAGE_SIZE = 50;

    @Autowired
    private SyncCompensateMapper syncCompensateMapper;

    @Override
    public Boolean saveToSync(List list, String serviceName, String tableName) {
        return saveToSync(list, serviceName, tableName, null);
    }

    @Override
    public Boolean saveToSync(List list, String serviceName, String tableName, String remarks) {
        ArrayList<SyncCompensate> syncCompensates = new ArrayList<>();
        for (Object object : list) {
            String jsonData = JSON.toJSONString(object);
            SyncCompensate syncCompensate = new SyncCompensate();
            syncCompensate.setJsonData(jsonData);
            syncCompensate.setToService(serviceName);
            syncCompensate.setToTable(tableName);
            syncCompensate.setRemarks(remarks);
            syncCompensates.add(syncCompensate);
        }
        return saveBatch(syncCompensates);
    }

    @Override
    public List<SyncCompensate> getSyncDataBySharding(Integer shardIndex, Integer shardTotal, Integer pageSize) {
        if (pageSize == null || pageSize.equals(0)) {
            pageSize = PAGE_SIZE;
        }
        return syncCompensateMapper.getSyncDataBySharding(shardIndex, shardTotal, pageSize);
    }

    @Override
    public void updateSyncData(SyncCompensate syncCompensate) {
        TableInfo tableInfo = TableInfoHelper.getTableInfo(syncCompensate.getToTable());
        Class<?> entityType = tableInfo.getEntityType();
        Object o = JSON.parseObject(syncCompensate.getJsonData(), entityType);
        IMppService bean = (IMppService) SpringContextUtils.getBean(syncCompensate.getToService());
        boolean b = bean.saveOrUpdateByMultiId(o);
        if (b) {
            syncCompensate.setDelFlag(1);
            updateById(syncCompensate);
        }
    }

}
